// pages/activeReportDetail/index.ts

import { fontSizeCalc, handleCode, handleErrCode } from "../../utils/util";
import { adoptSubmit, adoptSubmitScore, getCuesSubmitDetails } from "../../service/api/api-cues-submit";
import {
  adoptAccountList,
  adoptActive,
  adoptActiveScore,
  adoptInstructAccountPageList, adoptInstructAccountUpdate,
  getCuesActiveDetails,
  getCuesActiveSelectDetails,
  updateAdoptInstructDescribes
} from "../../service/api/api-cues-active";
import { saveCancelAdopt } from "../../service/api/api-cues-adopt";

const rules = [{
  name: "score",
  rule: ["required", "isAmount", "range:[0.01,100]"],
  msg: ["积分不能为空", "请输入数字，保留两位小数", "范围0.01-100"]
}]

let appointUserIds = new Set();// 选中的用户id

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,// 上报id
    type: 0,// 上报类型
    report: {},// 上报详情
    access: {} as any,// 当前用户权限
    currentUser: {},// 当前用户信息
    index: '',//上报index
    options: '',
    isCanAdopt: false,// 是否是可以录用
    isShowScore: false,// 是否显示评分
    isShowAdopt: false,// 是否显示自己录用
    isShowManageAdopt: false,// 是否显示录用
    isShowAdoptContent: false,// 是否显示录用内容
    isShowAdoptCount: false,// 是否显示录用次数
    isShowAdoptCountClick: false,// 是否显示录用点击查看
    isShowTopicContent: false,// 是否显示选题内容
    imgUrl: [],// 图片Url
    adoptRecordsList: [],// 录用记录列表
    adoptRecordsListBack: [],// 录用记录备份列表
    adoptInstructAccountList: [],// 可指派的用户列表
    adoptInstructAccountListBack: [],// 可指派的用户列表备份
    checkedAppointUserIds: [],// 编辑的时候默认选中
    galleryShow: false,// 是否显示图片预览

    drawerVisible: false,// 右侧抽屉是否显示
    drawerSecVisible: false,// 右侧第二抽屉是否显示

    directionsVisible: false,//右侧指令描述抽屉是否显示
    adoptAccountId: 0,//收录人id
    adoptDetails: {},//收录人详情
    modal: false,// 是否显示弹窗
    modalReward: '',// 弹窗输入的积分
    cancleInput: '',//取消描述输入框内容
    hasTips: false,// 是否已经提示过了
    cancelVisible: false,//是否显示取消指派框
    currentTop: 0,// 上面收缩显示
    currentMid: 1,// 中间收缩显示
    currentBot: 0,// 下面收缩显示

    navigateType: '',//是否为收录库到详情

    labelSize: fontSizeCalc(28),
    inputSize: fontSizeCalc(32),
    btnWidth: fontSizeCalc(200) + 'rpx',
    btnHeight: fontSizeCalc(60) + 'rpx',
    btnLineHeight: fontSizeCalc(36) + 'rpx',
    tagSize: fontSizeCalc(20) + 'rpx',

    searchText: "",// 搜索关键字
    cancleId: '',//取消描述的id
    instructDescribes: '',//指令描述
    selectedAccountRows: [],//选中指派的人
    instructDescribesAccountList: [],
    checkedAppointAccountUserIds: [],
  },
  //取消描述输入框内容提交
  async handleSubmitCancleInput() {
    const response = await saveCancelAdopt({
      id: this.data.cancleId,
      describes: this.data.cancleInput
    })
    if (response.code == 0) {
      wx.showToast({
        title: '取消成功',
      })
      var pages = getCurrentPages();
      var Page = pages[pages.length - 1];//当前页
      var prevPage = pages[pages.length - 2];  //上一个页面
      var info = prevPage.data.reportList //取上页data里的数据也可以修改
      var index = this.data.index;
      var cancelAccountId = this.data.cancleId;
      info[index].adoptCancelAccountId = cancelAccountId;
      info[index].adoptCancelAccountName = this.data.adoptDetails?.cancelAccountName;
      info[index].adoptCancelTime = this.data.adoptDetails?.cancelTime;
      info[index].adoptCancelDescribes = this.data.cancleInput;
      prevPage.setData({
        reportList: info
      });
      this.handleCancle()
      return true;
    } else {
      wx.showToast({
        title: '取消失败',
      })
      this.handleCancle()
      return false;
    }
  },
  //关闭取消描述输入框内容提交
  handleCancle() {
    this.setData({
      cancelVisible: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { id = 0, type = 0, table = '', adoptAccountId = 0, index = 0 } = options;
    console.log(options);

    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      id,
      type,
      adoptAccountId,
      index,
      navigateType: table,
      isCanAdopt: (access.线索上报x主动报送x配置x管理员 || access.线索上报x主动报送x配置x需求者) && access.线索上报x主动报送x选题列表x收录线索,
      isShowAdopt: access.线索上报x主动报送x配置x需求者 && access.线索上报x主动报送x选题列表x收录线索,
      isShowManageAdopt:  access.线索上报x主动报送x配置x管理员,
      isShowAdoptContent: access.线索上报x主动报送x选题列表x收录线索,
      isShowAdoptCount: access.线索上报x主动报送x选题列表x收录线索,// 是否显示录用次数
      isShowAdoptCountClick: (access.线索上报x主动报送x配置x管理员 || access.线索上报x主动报送x配置x需求者) && access.线索上报x主动报送x选题列表x收录线索,// 是否显示录用点击查看
      isShowScore: access.线索上报x主动报送x配置x管理员 && access.线索上报x主动报送x选题列表x评分线索,
      isShowTopicContent: type == 1,// 只有线索征集才有这个显示
      currentUser,
      options: JSON.stringify(options)
    })
    this.getReportDetail(id);
    if (this.data.navigateType == 'adopt') {
      this.getReportSelect(id);
    }
  },

  /**
   * 通过id获取子任务列表
   * @param id
   * @param hiddenLoading
   */
  async getReportDetail(id, hiddenLoading = false) {
    let _that = this;
    !hiddenLoading && wx.showLoading({
      title: '查询中...'
    })
    // 执行搜索函数
    await _that.handleFunType(1)({
      id,
    }).then(async (response) => {
      let report = response.data || {};
      report.attachment = this.handleAttachmentType(report.articleAttachments || [], report)
      _that.setData({
        report
      })
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      !hiddenLoading && wx.hideLoading();
      // if (!_that.data.hasTips){
      //     wx.showToast({
      //         title: '长按支持复制文章内容',
      //         icon: "none",
      //         duration: 1500
      //     })
      //     _that.setData({
      //         hasTips: true
      //     })
      // }
    })
  },

  /**
   * 通过id获取子任务列表
   * @param id
   * @param hiddenLoading
   */
  async getReportSelect(id, hiddenLoading = false) {
    let _that = this;
    !hiddenLoading && wx.showLoading({
      title: '查询中...'
    })
    // 执行搜索函数
    await getCuesActiveSelectDetails({
      articleId: id, adoptAccountId: this.data.adoptAccountId, type: this.data.type
    }).then(async (response) => {
      let adoptDetails = response.data || {};
      _that.setData({
        adoptDetails,
        instructDescribes: adoptDetails.instructDescribes || ''
      })
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      !hiddenLoading && wx.hideLoading();
    })
  },
  /**
   * 录用与不录用
   */
  async setReportAdoptFun(params) {
    let _that = this;
    if (!_that.data.isCanAdopt) {
      return
    }
    const { isSelfAdopt, id } = this.data.report;
    const tips = isSelfAdopt === 1 ? '取消录用' : '录用';
    wx.showLoading({
      title: tips + '中...'
    })
    // 执行搜索函数
    await _that.handleFunType(2)(params).then(async (response) => {
      handleCode(response, tips + '成功');
      setTimeout(() => {
        _that.getReportDetail(id);
      }, 500)
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
      _that.modalCancel();
    })
  },

  /**
   * 评分
   */
  async setReportScoreFun(params) {
    let _that = this;
    if (!_that.data.isShowScore) {
      return
    }
    wx.showLoading({
      title: '请稍候...'
    })
    // 执行搜索函数
    await _that.handleFunType(3)(params).then(async (response) => {
      handleCode(response, '评分成功');
      setTimeout(() => {
        _that.getReportDetail(params.id);
      }, 500)
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
      _that.modalCancel();
    })
  },

  /**
   * 获取录用列表
   */
  async getAdoptListFun() {
    let _that = this;
    const { id } = this.data.report;
    wx.showLoading({
      title: '查询中...'
    })
    // 执行搜索函数
    await adoptAccountList({
      articleId: id,
    }).then(async (response) => {
      _that.setData({
        adoptRecordsList: response.data || []
      })
      console.log(_that.data.adoptRecordsList);
      _that.showDrawer()
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
    })
  },

  /**
   * 获取录用列表
   */
  async getAdoptInstructAccountListFun() {
    let _that = this;
    const { id } = this.data.report;
    wx.showLoading({
      title: '查询中...'
    })
    await adoptInstructAccountPageList({
      articleId: id,
      current: 1,
      pageSize: 100,
    }).then(async (response) => {
      _that.setData({
        adoptInstructAccountList: _that.readyList(response?.data?.data || [])
      })

      // 处理一下选中的问题
      _that.data.adoptInstructAccountList.forEach(item => {
        _that.getChildrenValue(item)
      })
      console.log(appointUserIds);

      _that.showSecDrawer()
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
    })
  },

  /**
   * 设置录用更新
   */
  async adoptInstructAccountUpdateFun() {
    let _that = this;
    const { id } = this.data.report;
    wx.showLoading({
      title: '保存中...'
    })
    console.log(_that.data.checkedAppointUserIds);
    await adoptInstructAccountUpdate({
      accounts: _that.data.checkedAppointUserIds,
      articleId: id,
      type: Number(_that.data.type),// 类型区分 1:线索征集，2:主动报送
    }).then(async (response) => {
      handleCode(response, '保存成功');
      _that.closeSecDrawer();
      setTimeout(() => {
        _that.getAdoptListFun();
        _that.getReportDetail(id, true);
      }, 500)
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
    })
  },


  /**
   * 处理一下附件内容
   * @param list
   * @param voucherType
   */
  handleAttachmentType(list = [], { isImage, isFile }) {
    return list.map(item => {
      let attachmentName = '';
      // if (isImage === 1) {
      let { content = '' } = item;
      const hashIndex = content?.indexOf('?');
      content = hashIndex !== -1 ? content?.substring(0, hashIndex) : content;
      attachmentName = decodeURI((content.split('/').pop() || '').replace(/[\?].*$/g, ''));
      // }
      return {
        ...item,
        attachmentName
      }
    })
  },

  /**
   * 附件点击
   */
  attachmentItemClick(e: any) {
    const { attachment = [] } = this.data.report || {};
    this.showGalleryFun(
      attachment.map(item => {
        return {
          src: item.content,
          desc: item.voucherName
        }
      }))
  },

  /**
   * 显示弹窗弹窗
   */
  showModal() {
    const report = this.data.report;
    this.setData({
      modal: true,
      modalReward: report.score ?? 0,
    })
  },
  //显示取消指派框
  onOpenCancelVisible(e: any) {
    this.setData({
      cancelVisible: true,
      cancleId: e.currentTarget.dataset.id
    })
  },
  /**
   * 关闭弹窗弹窗
   */
  modalCancel() {
    this.setData({
      modal: false,
      modalReward: '',
    })
  },

  /**
   * 收录确认弹窗
   */
  modalConfirmFun() {
    const { report, modalReward } = this.data || {}
    let formData = {
      score: modalReward
    };
    this.selectComponent("#form").validate(formData, rules).then(res => {
      this.setReportScoreFun({ ...formData, id: report.id || 0 })
    }).catch(errors => {
      console.log(errors)
    })
  },

  /**
   * 收录确认弹窗
   */
  confirmFun() {
    const report = this.data.report || {};
    this.setReportAdoptFun({ id: report.id || 0 })
  },

  /**
   * 显示弹窗弹窗
   */
  showGalleryFun(imgUrl: any) {
    this.setData({
      galleryShow: true,
      imgUrl,
    })
  },

  /**
   * 关闭弹窗弹窗
   */
  hideGalleryFun() {
    this.setData({
      galleryShow: false,
      imgUrl: [],
    })
  },

  /**
   * 改变collapse
   * @param e
   */
  changeCollapse(e: any) {
    const curTag = e.currentTarget.dataset.item || '';
    this.setData({
      [curTag]: this.data[curTag] === 0 ? 1 : 0
    })
  },

  /**
   * 显示侧面抽屉
   */
  showDrawer() {
    this.setData({
      drawerVisible: true,
      adoptRecordsListBack: this.data.adoptRecordsList
    })
  },

  /**
   * 关闭抽屉
   */
  closeDrawer() {
    this.setData({
      drawerVisible: false,
      adoptRecordsList: [],
      adoptRecordsListBack: [],
    })
  },

  /**
   * 显示侧面抽屉
   */
  showSecDrawer() {
    this.setData({
      drawerSecVisible: true,
      adoptInstructAccountListBack: this.data.adoptInstructAccountList
    })
  },

  /**
   * 关闭抽屉
   */
  closeSecDrawer() {
    // appointUserIds.clear();
    this.setData({
      drawerSecVisible: false,
      adoptInstructAccountList: [],
      adoptInstructAccountListBack: [],
    })
  },

  /**
  * 显示指令指派抽屉
  */
  async showDirectDrawer() {
    let _that = this;
    const { id } = this.data.report;
    _that.setData({
      instructDescribes: ''
    })
    setTimeout(() => {
      _that.getAdoptListFun();
    }, 100)

    setTimeout(() => {
      _that.data.adoptRecordsList.map((item) => {
        item.checked = true
        return item
      })//加入选择字段
      const newList = _that.data.adoptRecordsList.filter(item => {
        if (item.isInstruct === 0) {
          return false; // 不满足条件时，返回 false，即移除该项
        }
        return true; // 满足条件时，返回 true，保留该项
      });
      _that.setData({
        instructDescribesAccountList: newList,
      })
      _that.data.instructDescribesAccountList.forEach(item => {
        _that.getChildrenValue(item);
      });
      if (_that.data.instructDescribesAccountList.length === 0) {
        wx.showToast({
          title: '指派人不能为空',
          icon: "none",
          duration: 1500
        })
        return;
      }
      this.setData({
        directionsVisible: true,
      })
    }, 1000)
    var userListIds = _that.data.checkedAppointUserIds.length === 0 ? appointUserIds : _that.data.checkedAppointUserIds
    await adoptInstructAccountUpdate({
      accounts: userListIds,
      articleId: id,
      type: Number(_that.data.type),// 类型区分 1:线索征集，2:主动报送
    }).then(async (response) => {

    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
    })

  },

  /**
   * 关闭指令指派抽屉
   */
  closeDirectDrawer() {
    this.setData({
      directionsVisible: false,
    })
  },
  /**
   * 提交指派指令
   */
  async handleOk() {
    let _that = this;
    const { id } = this.data.report;
    wx.showLoading({
      title: '保存中...'
    })
    console.log(_that.data.checkedAppointAccountUserIds);

    await updateAdoptInstructDescribes({
      accounts: _that.data.checkedAppointAccountUserIds,
      articleId: id,
      instructDescribes: _that.data.instructDescribes,
      type: Number(_that.data.type),// 类型区分 1:线索征集，2:主动报送
    }).then(async (response) => {
      handleCode(response, '保存成功');
      _that.closeDirectDrawer();
      _that.closeSecDrawer();
      setTimeout(() => {
        _that.getAdoptListFun();
        _that.getReportDetail(id, true);
      }, 500)
    }).catch(error => {
      console.warn(error)
      handleErrCode()
    }).finally(() => {
      wx.hideLoading();
    })
  },
  /**
   * 单位树节点 修改
   */
  adoptItemCheck(e: any) {

    let data = e.currentTarget.dataset.item || {};
    console.log(data);

    if (data.disabled) {// 禁用不可选
      return
    }
    let dataList = this.data.adoptInstructAccountList;
    const targetIndex = dataList.findIndex(item => item.accountId === data.accountId);// 找到下标
    data.checked = !data.checked;// 取反

    this.getChildrenValue(data);// 处理选中一下
    dataList[targetIndex] = data;// 替换一下
    this.setData({
      checkedAppointUserIds: Array.from(appointUserIds),
      adoptInstructAccountList: dataList,// 更新列表
    })
  },
  /**
  * 单位树节点 修改
  */
  adoptItemAccountCheck(e: any) {
    let data = e.currentTarget.dataset.item || {};
    console.log(data);

    if (data.disabled) {// 禁用不可选
      return
    }
    let dataList = this.data.instructDescribesAccountList;
    const targetIndex = dataList.findIndex(item => item.accountId === data.accountId);// 找到下标
    data.checked = !data.checked;// 取反
    this.getChildrenValue(data);// 处理选中一下
    dataList[targetIndex] = data;// 替换一下
    this.setData({
      checkedAppointAccountUserIds: Array.from(appointUserIds),
      instructDescribesAccountList: dataList,// 更新列表
    })
    console.log(this.data.checkedAppointAccountUserIds);

  },

  /**
   * 获取子类值
   */
  getChildrenValue({ checked, accountId }) {
    if (accountId) {
      if (checked) {// 选中了，就都加进去
        appointUserIds.add(accountId);
      } else {// 没选中，找一下删掉
        appointUserIds.delete(accountId)
      }
    }
  },

  /**
* 长按复制内容
*/
  copyName(e: any) {
    let text = e.currentTarget.dataset?.text || '';
    text = text.replace(/<[^>]*>/g, '');
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.showToast({
          title: '复制标题成功',
          icon: "none",
          duration: 1500
        })
      }
    });
  },


  /**
   * 长按复制内容
   */
  copyContent(e: any) {
    let text = e.currentTarget.dataset?.text || '';
    text = text.replace(/<[^>]*>/g, '');
    const mpHtml = this.selectComponent('#mpHtml');
    wx.setClipboardData({
      data: mpHtml?.getText() || text,
      success: function (res) {
        wx.showToast({
          title: '复制内容成功',
          icon: "none",
          duration: 1500
        })
      }
    });
  },

  /**
   * 开始搜索
   * @param detail
   */
  searchFun({ detail = { value: '' } }) {
    const all = !detail.value;// 输入一些空值就去查全部
    this.setData({
      searchText: detail.value,
      adoptRecordsList: this.data.adoptRecordsListBack.filter(
        item => all || item?.accountName?.includes(detail.value)
      ),
    })
  },

  /**
   * 搜索取消
   */
  searchCancel() {
    this.setData({
      searchText: "",
      adoptRecordsList: this.data.adoptRecordsListBack
    })
  },

  /**
   * 处理调用函数类型
   */
  handleFunType(type) {
    let target
    switch (type) {
      case 1:// 获取详情
        target = (this.data.isShowTopicContent ? getCuesSubmitDetails : getCuesActiveDetails)
        break;
      case 2:// 录用
        target = (this.data.isShowTopicContent ? adoptSubmit : adoptActive)
        break;
      case 3:// 评分
        target = (this.data.isShowTopicContent ? adoptSubmitScore : adoptActiveScore)
        break;
    }
    return target
  },

  /**
   * 预备Tree结构数据
   * @param data
   */
  readyList(data): any {
    let treeData = [];
    if (Array.isArray(data)) {
      treeData = data.map(item => {
        const { selected, disabled, isInstruct } = item;
        let newItem = {
          checked: selected === 1,// 默认选中
          disabled: disabled === 1,// 是否禁用
          tagType: isInstruct === 1 ? 'warning' : 'green',// tag样式
          tagText: isInstruct === 1 ? '指令' : '自主',// tag样式
        };
        // 禁用的话，那就要处理一下灰色
        if (newItem.disabled) {
          newItem.tagType = 'gray'
          newItem.tagText = '自主，不可选择'
        }
        return { ...item, ...newItem }
      });
    }
    return treeData;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  taskExecuteShareFun() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  }
})